<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>游戏事件统计</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        h1, h2 {
            color: #333;
        }
        .container {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
        }
        .card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            padding: 20px;
            flex: 1;
            min-width: 300px;
        }
        .source-selector {
            margin-bottom: 20px;
            padding: 15px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        select {
            padding: 8px;
            border-radius: 4px;
            border: 1px solid #ddd;
            margin-right: 10px;
        }
        button {
            padding: 8px 16px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }
        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        th {
            background-color: #f2f2f2;
        }
        .loading {
            text-align: center;
            padding: 20px;
            font-style: italic;
            color: #666;
        }
    </style>
</head>
<body>
    <h1>游戏事件统计</h1>
    
    <div style="margin-bottom: 20px;">
        <a href="javascript:void(0)" onclick="navigateTo('/')" style="margin-right: 15px; color: #4CAF50; text-decoration: none;">首页</a>
        <a href="javascript:void(0)" onclick="navigateTo('/stats')" style="margin-right: 15px; color: #4CAF50; text-decoration: none;">统计页面</a>
        <a href="javascript:void(0)" onclick="navigateTo('/sources')" style="margin-right: 15px; color: #4CAF50; text-decoration: none;">脚本来源管理</a>
    </div>
    
    <div class="source-selector">
        <h2>选择脚本来源</h2>
        <select id="sourceSelect">
            <option value="">所有来源</option>
        </select>
        <button id="refreshBtn">刷新数据</button>
    </div>
    
    <div class="container">
        <div class="card">
            <h2>事件计数</h2>
            <div id="eventCounts" class="loading">加载中...</div>
        </div>
        
        <div class="card">
            <h2>事件间平均时间</h2>
            <div id="avgTimeBetweenEvents" class="loading">加载中...</div>
        </div>
    </div>
    
    <div class="card">
        <h2>最近事件时间</h2>
        <div id="lastEventTimes" class="loading">加载中...</div>
    </div>
    
    <script>
        // 使用相对URL，避免协议问题
        function navigateTo(path) {
            window.location.href = path;
        }
        
        document.addEventListener('DOMContentLoaded', function() {
            // 使用相对URL，避免协议问题
            // 加载脚本来源列表
            fetch('/api/events/sources')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const sourceSelect = document.getElementById('sourceSelect');
                        data.sources.forEach(source => {
                            const option = document.createElement('option');
                            option.value = source;
                            option.textContent = source;
                            sourceSelect.appendChild(option);
                        });
                        
                        // 初始加载数据
                        loadStats();
                    }
                })
                .catch(error => console.error('加载脚本来源失败:', error));
            
            // 刷新按钮点击事件
            document.getElementById('refreshBtn').addEventListener('click', loadStats);
            
            // 加载统计数据
            function loadStats() {
                const sourceSelect = document.getElementById('sourceSelect');
                const selectedSource = sourceSelect.value;
                
                let url = '/api/events/stats';
                if (selectedSource) {
                    url += `?script_source=${encodeURIComponent(selectedSource)}`;
                }
                
                // 设置加载状态
                document.getElementById('eventCounts').innerHTML = '<div class="loading">加载中...</div>';
                document.getElementById('avgTimeBetweenEvents').innerHTML = '<div class="loading">加载中...</div>';
                document.getElementById('lastEventTimes').innerHTML = '<div class="loading">加载中...</div>';
                
                fetch(url)
                    .then(response => response.json())
                    .then(data => {
                        console.log('API返回数据:', data); // 添加调试日志
                        
                        if (data.success) {
                            // 添加调试信息
                            document.getElementById('eventCounts').innerHTML = 
                                '<div style="margin-bottom:10px;padding:5px;background:#f8f9fa;border:1px solid #ddd;border-radius:4px;">' +
                                '<strong>调试信息:</strong> ' + 
                                '<pre style="overflow:auto;max-height:100px;">' + JSON.stringify(data.stats.event_counts, null, 2) + '</pre>' +
                                '</div>';
                            
                            // 渲染事件计数
                            renderEventCounts(data.stats.event_counts);
                            
                            // 渲染事件间平均时间
                            renderAvgTimeBetweenEvents(data.stats.avg_time_between_events);
                            
                            // 渲染最近事件时间
                            renderLastEventTimes(data.stats.last_event_times);
                        } else {
                            console.error('API返回错误:', data);
                        }
                    })
                    .catch(error => {
                        console.error('加载统计数据失败:', error);
                        document.getElementById('eventCounts').innerHTML = '<div>加载失败</div>';
                        document.getElementById('avgTimeBetweenEvents').innerHTML = '<div>加载失败</div>';
                        document.getElementById('lastEventTimes').innerHTML = '<div>加载失败</div>';
                    });
            }
            
            // 渲染事件计数表格
            function renderEventCounts(eventCounts) {
                if (!eventCounts || eventCounts.length === 0) {
                    document.getElementById('eventCounts').innerHTML = '<div>暂无数据</div>';
                    return;
                }
                
                let html = `
                    <table>
                        <thead>
                            <tr>
                                <th>脚本来源</th>
                                <th>事件类型</th>
                                <th>计数</th>
                            </tr>
                        </thead>
                        <tbody>
                `;
                
                eventCounts.forEach(item => {
                    html += `
                        <tr>
                            <td>${item.script_source || '未知'}</td>
                            <td>${item.event_type}</td>
                            <td>${item.count}</td>
                        </tr>
                    `;
                });
                
                html += `
                        </tbody>
                    </table>
                `;
                
                document.getElementById('eventCounts').innerHTML = html;
            }
            
            // 渲染事件间平均时间表格
            function renderAvgTimeBetweenEvents(avgTimeBetweenEvents) {
                if (!avgTimeBetweenEvents || avgTimeBetweenEvents.length === 0) {
                    document.getElementById('avgTimeBetweenEvents').innerHTML = '<div>暂无数据</div>';
                    return;
                }
                
                let html = `
                    <table>
                        <thead>
                            <tr>
                                <th>脚本来源</th>
                                <th>事件类型</th>
                                <th>平均间隔 (毫秒)</th>
                                <th>平均间隔 (可读)</th>
                            </tr>
                        </thead>
                        <tbody>
                `;
                
                avgTimeBetweenEvents.forEach(item => {
                    const seconds = Math.floor(item.avg_time_diff_ms / 1000);
                    const minutes = Math.floor(seconds / 60);
                    const hours = Math.floor(minutes / 60);
                    
                    let readableTime = '';
                    if (hours > 0) {
                        readableTime = `${hours}小时${minutes % 60}分${seconds % 60}秒`;
                    } else if (minutes > 0) {
                        readableTime = `${minutes}分${seconds % 60}秒`;
                    } else {
                        readableTime = `${seconds}秒`;
                    }
                    
                    html += `
                        <tr>
                            <td>${item.script_source || '未知'}</td>
                            <td>${item.event_type}</td>
                            <td>${Math.round(item.avg_time_diff_ms)}</td>
                            <td>${readableTime}</td>
                        </tr>
                    `;
                });
                
                html += `
                        </tbody>
                    </table>
                `;
                
                document.getElementById('avgTimeBetweenEvents').innerHTML = html;
            }
            
            // 渲染最近事件时间表格
            function renderLastEventTimes(lastEventTimes) {
                if (!lastEventTimes || lastEventTimes.length === 0) {
                    document.getElementById('lastEventTimes').innerHTML = '<div>暂无数据</div>';
                    return;
                }
                
                let html = `
                    <table>
                        <thead>
                            <tr>
                                <th>脚本来源</th>
                                <th>事件类型</th>
                                <th>最近发生时间</th>
                            </tr>
                        </thead>
                        <tbody>
                `;
                
                lastEventTimes.forEach(item => {
                    html += `
                        <tr>
                            <td>${item.script_source || '未知'}</td>
                            <td>${item.event_type}</td>
                            <td>${item.formatted_time}</td>
                        </tr>
                    `;
                });
                
                html += `
                        </tbody>
                    </table>
                `;
                
                document.getElementById('lastEventTimes').innerHTML = html;
            }
        });
    </script>
</body>
</html>